import {useState} from "react";

// 超级管理员添加管理员

interface UseAddAdmin {
    addAdmin: (id: string, name: string, password: string) => Promise<void>;
    isLoading: boolean;
    error: string | null;
}

export function useAddAdmin(): UseAddAdmin {
    const [isLoading, setIsLoading] = useState(false);
    const [error, setError] = useState<string | null>(null);
    const token = localStorage.getItem('token');

    async function addAdmin(id: string, name: string, password: string): Promise<void> {
        setIsLoading(true);
        setError(null);
        try {
            if (!token) {
                setError('未提供授权令牌');
                return;
            }
            const response = await fetch('http://localhost:6868/superAdmin/addAdmin', {
                method: 'POST',
                headers: {
                    'Authorization': token!,
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({
                    id: id,
                    name: name,
                    password: password
                })
            });
            if (!response.ok) {
                throw new Error("添加管理员失败");
            }
        } catch (error) {
            setError((error as Error).message);
        } finally {
            setIsLoading(false);
        }
    };

    return {addAdmin, isLoading, error};
}
